<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea v-if="!inline" :id="tinymceId" class="tinymce-textarea"/>
    <div v-if="inline" :id="tinymceId" class="tinymce-textarea"/>
  </div>
</template>

<script>
    /**
     * docs:
     * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
     */

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
    const plugins = ['print preview paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons bdmap indent2em lineheight']
    const toolbar = ['undo redo fullscreen preview save code | bold italic underline strikethrough forecolor backcolor removeformat | fontselect fontsizeselect | alignleft aligncenter alignright alignjustify | indent2em outdent indent lineheight | bullist numlist | hr table insertfile image media link anchor codesample charmap emoticons insertdatetime bdmap | wordcount']
    // const full_toolbar = ['undo redo | bold italic underline strikethrough forecolor backcolor removeformat | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | indent2em outdent indent lineheight | bullist numlist | hr pagebreak | fullscreen preview save print code| table insertfile image media template link anchor codesample charmap emoticons insertdatetime bdmap | searchreplace wordcount ltr rtl'];
    const fonts = ['微软雅黑="Microsoft YaHei", "Helvetica Neue", "PingFang SC", sans-serif;', '宋体=simsun, serif;', '仿宋体=FangSong, serif;', '黑体=SimHei, sans-serif;', '苹果平方="PingFang SC", "Microsoft YaHei", sans-serif;', '小米字体="Helvetica Neue", Helvetica, Arial, "Microsoft Yahei", "Hiragino Sans GB", "Heiti SC", "WenQuanYi Micro Hei", sans-serif;', '知乎字体=BlinkMacSystemFont, "Helvetica Neue", "PingFang SC", "Microsoft YaHei", "Source Han Sans SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", sans-serif;'].join('') +
        'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats'
    // 可以自适应高度 autoresize
    // fullpage 编辑元数据和文档属性，包含title，keywords，description和文档编码charset。

    export default {
        name: 'Tinymce',
        props: {
            id: {
                type: String,
                default: function () {
                    return 'vue-tinymce-' + Number(new Date()) + (String((Math.random() * 1000).toFixed(0)))
                }
            },
            value: {
                type: String,
                default: ''
            },
            toolbar: {
                type: [Array, String, Boolean],
                default: toolbar
            },
            setup: {
                type: Function,
                default: () => {
                }
            },
            menubar: {
                type: [String, Boolean],
                default: 'file edit view insert format tools table help'
            },
            statusbar: {
                type: Boolean,
                default: false
            },
            quickbarsInsertToolbar: {
                type: [String, Boolean],
                default: false
            },
            quickbarsSelectionToolbar: {
                type: [String, Boolean],
                default: false
            },
            height: {
                type: [Number, String],
                required: false,
                default: 360
            },
            width: {
                type: [Number, String],
                required: false,
                default: 'auto'
            },
            inline: {
                type: Boolean,
                default: false
            },
            mobile: {
                type: Object,
                default: () => {
                    return {
                        theme: 'mobile',
                        plugins: plugins,
                        toolbar: toolbar
                    }
                }
            },
            contentCss: {
                type: String,
                default: ''
            },
            extraOptions: {
                type: Object,
                default: () => {
                }
            }
        },
        data () {
            return {
                hasChange: false,
                hasInit: false,
                tinymceId: this.id,
                fullscreen: false,
                languageTypeList: {
                    'en': 'en',
                    'zh': 'zh_CN',
                    'es': 'es_MX',
                    'ja': 'ja'
                }
            }
        },
        computed: {
            containerWidth () {
                const width = this.width
                if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
                    return `${width}px`
                }
                return width
            }
        },
        watch: {
            value (val) {
                if (!this.hasChange && this.hasInit) {
                    this.$nextTick(() =>
                        window.tinymce.get(this.tinymceId).setContent(val || ''))
                }
            }
        },
        mounted () {
            this.init()
        },
        activated () {
            if (window.tinymce) {
                this.initTinymce()
            }
        },
        deactivated () {
            this.destroyTinymce()
        },
        destroyed () {
            this.destroyTinymce()
        },
        methods: {
            init () {
                this.initTinymce()
            },
            initTinymce () {
                const _this = this
                window.tinymce.init({
                    selector: `#${this.tinymceId}`,
                    language: this.languageTypeList['zh'],
                    // 内联模式
                    inline: this.inline,
                    height: this.height,
                    body_class: 'panel-body ',
                    object_resizing: true,
                    toolbar: false,
                    toolbar_sticky: true,
                    toolbar_drawer: 'sliding',
                    menubar: this.menubar,
                    // quickbars_insert_toolbar: this.quickbarsInsertToolbar,
                    // quickbars_selection_toolbar: this.quickbarsSelectionToolbar,
                    statusbar: this.statusbar,
                    plugins: plugins,
                    link_context_toolbar: true,
                    branding: false, // 右下支持
                    autosave_ask_before_unload: true,
                    autosave_interval: '30s',
                    autosave_prefix: '{path}{query}-{id}-',
                    autosave_restore_when_empty: false,
                    autosave_retention: '2m',
                    end_container_on_empty_block: true,
                    powerpaste_word_import: 'clean',
                    // code_dialog_height: 450,
                    // code_dialog_width: 1000,
                    // advlist_bullet_styles: 'square',
                    // advlist_number_styles: 'default',
                    default_link_target: '_blank',
                    link_title: false,
                    target_list: false,
                    nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin

                    content_css: this.contentCss,
                    // 图片上传
                    image_advtab: true,
                    imagetools_cors_hosts: ['*'],

                    images_reuse_filename: true,
                    images_upload_url: process.env.VUE_APP_BASE_API + '/file/uploadForTinyMCE',
                    images_upload_base_path: process.env.VUE_APP_BASE_API + '/file/',
                    image_caption: true,
                    font_formats: fonts,
                    // 清除粘贴格式
                    paste_auto_cleanup_on_paste: true,
                    paste_remove_styles: true,
                    paste_remove_styles_if_webkit: true,
                    paste_strip_class_attributes: true,
                    // paste_preprocess: function (plugin, args) {
                    //     console.log(args.content)
                    //     args.content = args.content.replace(/<\/?.+?>/g, '')
                    //     console.log(args.content)
                    // },
                    init_instance_callback: editor => {
                        if (_this.value) {
                            editor.setContent(_this.value)
                        }
                        _this.hasInit = true
                        editor.on('NodeChange Change KeyUp SetContent', () => {
                            this.hasChange = true
                            this.$emit('input', editor.getContent({ format: 'text' }))
                            this.$emit('input-text', editor.getContent({ format: 'text' }))
                        })
                    },
                    setup (editor) {
                        editor.on('FullscreenStateChanged', (e) => {
                            _this.fullscreen = e.state
                        })
                        // 传入setup
                        _this.setup && _this.setup(editor)
                    },
                    save_onsavecallback: () => {
                        this.$emit('save')
                    },
                    ..._this.extraOptions
                })
            },
            destroyTinymce () {
                const tinymce = window.tinymce.get(this.tinymceId)
                if (this.fullscreen) {
                    tinymce.execCommand('mceFullScreen')
                }

                if (tinymce) {
                    tinymce.destroy()
                }
            },
            setContent (value) {
                window.tinymce.get(this.tinymceId).setContent(value)
            },
            getContent () {
                window.tinymce.get(this.tinymceId).getContent()
            },
            imageSuccessCBK (arr) {
                const _this = this
                arr.forEach(v => {
                    window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
                })
            },
            /**
             * 向光标处插入内容
             * 参考：https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#execcommand
             * @param value 插入的内容
             * @param ui True/false state if a UI (dialog) should be presented or not.
             */
            mceInsertContent (value, ui = false) {
                window.tinymce.get(this.tinymceId).execCommand('mceInsertContent', ui, value)
            },
            /**
             * 打开超链接窗口  要执行该命令必须先使用link插件
             * 参考：http://tinymce.ax-z.cn/plugins/link.php
             */
            mceInsertLink () {
                window.tinymce.get(this.tinymceId).execCommand('mceLink')
            }
        }
    }
</script>

<style scoped>

</style>
